<template>
  <div class="login_wrap">
    <div class="form_wrap">
      <el-form
          ref="formRef"
          :model="loginData"
          label-width="100px"
          class="demo-dynamic"
      >
        <el-form-item
            prop="username"
            label="用户名"
            :rules="[
        {
          required: true,
          message: '此项为必填项',
          trigger: 'blur',
        },
      ]"
        >
          <el-input v-model="loginData.username"/>
        </el-form-item>
        <el-form-item
            prop="password"
            label="密码"
            :rules="[
        {
          required: true,
          message: '此项为必填项',
          trigger: 'blur',
        },
      ]"
        >
          <el-input type="password" v-model="loginData.password"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login_btn" @click="handleLogin">登录</el-button>
          <p>{{ num }}</p>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import {reactive, toRefs} from "vue";
import {useStore} from "vuex"
import {useRouter} from "vue-router";
import {loginApi} from "@/util/request";

export default {
  name: "login",
  setup() {
    const store = useStore()
    const router = useRouter()
    const count = store.state.num.count
    const data = reactive({
      loginData: {
        username: "",
        password: "",
        token: ""
      },
      num: count,
      numCount: store.getters["num/countStatus"],
    })
    const handleLogin = () => {
      let t;
      loginApi(data.loginData).then(resData => {
        if (resData) {
          data.loginData.token = "Bearer " + resData.token;
          console.log("登录接口返回", resData);
          store.commit("setUserInfo", data.loginData);
          localStorage.setItem("userInfo", JSON.stringify(data.loginData));
          if (t) {
            clearTimeout(t)
          }
          t = setTimeout(() => {
            //跳转/user
            router.push({
              path: "/welcome"
            })
          }, 500);
        }
      })
    }
    // const  handleLogin=()=>{
    //   // store.commit("num/setCount",100);
    //   store.dispatch("num/setCountPromise",101).then(result=>{
    //     alert("修改成功。");
    //   }).catch(err=>{
    //     alert(err);
    //   });
    //   console.log(store.state.num.count)
    //   console.log( store.getters["num/countStatus"])
    // }
    return {
      ...toRefs(data),
      handleLogin,

    }
  }
}
</script>
<style scoped>
.login_wrap {
  width: 100%;
  height: 100vh;
  background: #42b983;
}

.form_wrap {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 30px 50px;
  border-radius: 5px;
}

.login_btn {
  display: block;
  margin: 10px auto;
}
</style>